package com.small.helper;

import com.small.anontation.Action;
import com.small.web.Handler;
import com.small.web.Request;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 控制器助手类
 * Created by fangzheng on 2018/1/30.
 */
public class ControllerHelper {
    /**
     * 存储请求与映射的关系
     */
    private static final Map<Request, Handler> ACTION_MAP = new HashMap<Request, Handler>();

    static {
        Set<Class<?>> controllers = ClassHelper.getControllerClassSet();
        if (!controllers.isEmpty()) {
            for (Class<?> controller : controllers) {
                Method[] methods = controller.getDeclaredMethods();
                if (methods.length > 0) {
                    for (Method method : methods) {
                        if (method.isAnnotationPresent(Action.class)) {//如果该方法带有@Action注解
                            Action action = method.getAnnotation(Action.class);
                            //action方法上的mapping串：@Action("get:/hello")
                            String mapping = action.value();
                            if (mapping.matches("\\w+:/\\w*")) {
                                String[] arrays = mapping.split(":");
                                if (null != arrays && arrays.length == 2) {
                                    String requestMethod = arrays[0];//请求方法：get/post
                                    String requestPath = arrays[1];//请求路径：hello.do
                                    Request request = new Request(requestMethod, requestPath);
                                    Handler handler = new Handler(controller, method);
                                    //将请求与映射放入MAP中
                                    ACTION_MAP.put(request, handler);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 从ACTION_MAP中获取handler
     *
     * @param requestMethod
     * @param requestPath
     * @return
     */
    public static Handler getHandler(String requestMethod, String requestPath) {
        Request request = new Request(requestMethod, requestPath);
        return ACTION_MAP.get(request);
    }

}
